<template>
    <Modal
        v-model="modal.show"
        :title="modal.title"
        :loading="modal.loading"
        @on-ok="saveReport"
        @on-cancel="hideModal"
    >
        <!-- <template slot-scope="props"> -->
        <Form ref="formValidate" :model="formValidate" :label-width="80" :rules="ruleValidate">
            <template v-if="type === 'import'">
                <FormItem label="上传文件" prop="fileId" key="fileId">
                    <Upload
                        ref="uploadFile"
                        :action="upLoadUrl"
                        :before-upload="handleUploadIcon"
                        style="display: inline-block;"
                    >
                        <Button icon="ios-cloud-upload-outline" :disabled="loading"
                            >选择文件</Button
                        >
                    </Upload>
                    <WarningTip style="display: inline-block;">
                        <p style="white-space: normal;word-break: break-all;">
                            支持上传类型:{{ formatArr && formatArr.toString() }}
                        </p>
                        <p style="white-space: normal;">
                            文件名称:不能包含下列任意英文字符 \ / : * ? " < > |，长度为1-64个字符
                        </p>
                    </WarningTip>
                    <div v-if="formItem.file !== null">
                        <p>文件名: {{ formItem.file.name }}</p>
                        <template v-if="showProgress">
                            <p>大小：<span v-text="fileSize"></span></p>
                            <Progress :percent="progress"></Progress>
                            <p>速度：<span v-text="speed"></span></p>
                        </template>
                    </div>
                </FormItem>
                <FormItem label="备注" prop="remark">
                    <QuillEditorItem
                        :dataValue="formValidate.remark"
                        type="questionName"
                        class="fix-height-editor"
                        @editorChange="editorChange"
                    />
                </FormItem>
            </template>
            <template v-else>
                <FormItem label="小节名称" prop="name">
                    <Input v-model="formValidate.name" placeholder="请输入小节名称"></Input>
                </FormItem>
                <FormItem label="小结内容" prop="remark">
                    <QuillEditorItem
                        :dataValue="formValidate.remark"
                        type="questionName"
                        class="fix-height-editor"
                        @editorChange="editorChange"
                    />
                </FormItem>
            </template>
        </Form>
        <!-- </template> -->
    </Modal>
</template>
<script>
import QuillEditorItem from '@/components/quillEditor/index.vue';
import ItemUpload from '@/components/item-upload';
import { addReport, updateReport } from '../../api/report.js';
import { mapState } from 'vuex';
import { promised } from 'q';
export default {
    name: 'EditModal',
    components: { QuillEditorItem, ItemUpload },
    mixins: [],
    // inject: ['parent'],
    props: {
        contentId: {
            type: String,
            default: ''
        },
        taskId: {
            type: String,
            default: ''
        },
        title: {
            type: String,
            default: '科研文档'
        }
    },
    data() {
        return {
            type: '',
            modal: {
                show: false,
                data: '',
                loading: true
            },
            formValidate: {
                contentId: this.contentId,
                taskId:this.taskId,
                fileId: '',
                fileName: '',
                id: '',
                name: '',
                path: '',
                remark: '',
                type: 0
            },
            ruleValidate: {
                name: [{ required: true, message: '请输入小结名称', trigger: 'blur' }],
                // remark: [
                //     {
                //         required: true,
                //         message: '请输入内容',
                //         trigger: 'change'
                //     }
                // ],
                fileId: [{ required: true, message: '请选择文件', trigger: 'blur' }]
            },
            // 导入路径
            imageArr: [
                'jpeg',
                'jpg',
                'jpe',
                'png',
                'gif',
                'tiff',
                'bmp',
                'dwg',
                'psd',
                'ico',
                'rgb',
                'ogx',
                'pcx',
                'mdi',
                'tif',
                'pgm',
                'cmx',
                'webp'
            ],
            docsArr: [
                'pdf',
                'doc',
                'docx',
                // 'xls',
                // 'xlsx',
                // 'xla',
                'pptx',
                // 'pps',
                'ppt',
                // 'rtf',
                'txt',
                'md'
            ],
            othersArr: ['zip', 'bz2', '7z', 'cab', 'rar', 'epub'],
            packageArr: ['zip', 'rar'],
            videoArr: [
                'mp4',
                'webm',
                'ogv',
                'ogg',
                '3gp',
                '3g2',
                'm4v',
                'mpg',
                'vob',
                'fli',
                'mkv',
                'asf',
                'asx',
                'wmv',
                'flv',
                'avi'
            ],
            audioArr: [
                'm4a',
                'sil',
                'ra',
                'ram',
                'au',
                'wma',
                'aiff',
                'mp3',
                'mid',
                'midi',
                'rmi',
                'oga',
                'wav',
                'caf',
                'flac',
                'adp',
                'aac'
            ],
            upLoadUrl: '/api/minio/upload/permanent',
            uploadHeader: {
                Authorization: localStorage.token,
                Accept: '*/*'
            },
            formItem: {
                file: null,
                type: '',
                bucket: ''
            },
            speed: 0,
            loaded: 0,
            fileSize: 0,
            progress: 0,
            loading: false,
            showProgress: false
        };
    },
    computed: {
        ...mapState('user', ['nickname']),
        formatArr() {
            return this.docsArr //[...this.docsArr, ...this.videoArr, ...this.packageArr];
        }
    },
    watch: {},
    mounted() {
        this._formValidate = { ...this.formValidate };
    },
    methods: {
        showModal(data, type) {
            let name = this.title;
            this.type = type;
            this.modal.show = true;
            this.op = data ? 'update' : 'add';
            let txt = type === 'import' ? '上传' : '创建';
            if (!data) {
                this.modal.title = `${txt}${name}`;
                this.resetField();
                this.formValidate.iconPath = '';
            } else {
                this.modal.title = `修改${name}`;
                this.showProgress = false;
                this.formItem.file = {
                    name: data.fileName
                };
                this.formValidate = {
                    ...data
                };
            }
        },
        editorChange(value) {
            this.formValidate.remark = value;
        },
        resetField() {
            this.formValidate = { ...this._formValidate };
            this.$refs.formValidate.resetFields();
        },
        getUploadFile(data) {
            let { fileId, fileName, filePath } = file;
            this.formValidate.fileId = fileId;
            this.formValidate.fileName = fileName;
            this.formValidate.path = filePath;
        },
        async saveReport() {
            if (this.type === 'import') {
                let file = await this.formBtn();
                Object.assign(this.formValidate, file);
                this.formValidate.name = file.fileName;
            }
            this.$refs.formValidate.validate((valid) => {
                if (valid) {
                    let params = {
                        ...this.formValidate,
                        contentId: this.contentId,
                        type: this.type == 'import' ? 1 : 0
                    };
                    if (this.op == 'add') {
                        addReport(params)
                            .then(({ code, message }) => {
                                if (code === 1) {
                                    this.$Message.info('创建成功');
                                    this.hideModal();
                                    this.$emit('refresh');
                                } else {
                                    this.$Message.error(message);
                                }
                                this.cancelLoading();
                            })
                            .catch((error) => {
                                this.cancelLoading();
                            });
                    } else {
                        updateReport(params.id, params)
                            .then(({ code, message }) => {
                                if (code === 1) {
                                    this.$Message.info('修改成功');
                                    this.hideModal();
                                    this.$emit('refresh');
                                } else {
                                    this.$Message.error(message);
                                }
                                this.cancelLoading();
                            })
                            .catch((error) => {
                                this.cancelLoading();
                            });
                    }
                } else {
                    this.cancelLoading();
                }
            });
        },
        hideModal() {
            this.modal.show = false;
        },
        cancelLoading() {
            this.modal.loading = false;
            setTimeout(() => {
                this.modal.loading = true;
            });
        },
        getFileName(name) {
            return name.substring(0, name.lastIndexOf('.'));
        },
        handleUploadIcon(file) {
            this.speed = 0;
            this.loaded = 0;
            this.progress = 0;
            this.isUpdataing = true;
            this.showProgress = true;
            this.onlyFileName = file.name + '_' + new Date().getTime();
            if (file) {
                if (file.size > 1024 * 1024) {
                    this.fileSize =
                        (Math.round((file.size * 100) / (1024 * 1024)) / 100).toString() + 'MB';
                } else {
                    this.fileSize = (Math.round((file.size * 100) / 1024) / 100).toString() + 'KB';
                }
                //验证名称
                if (file.name) {
                    let name = this.getFileName(file.name);
                    let reg = new RegExp('/[\\/:*?"<>|]/gi');
                    if (reg.test(name) || name.length > 64) {
                        this.$Message.warning('文件名不能包含下列任意英文字符 \ / : * ? " < > |，长度为1-64个字符')
                        return false;
                    }
                    // let reg = new RegExp('^[\u4E00-\u9FA5a-zA-Z0-9_ -]*$');
                    // if (!reg.test(name) || name.length > 64) {
                    //     this.$Message.error({
                    //         content:
                    //             '文件名称只能包含中文、英文、数字、下划线、-，名称长度为1-64个字符',
                    //         duration: 3
                    //     });
                    //     return false;
                    // }
                }
            }
            let exceededNum = file.name.lastIndexOf('.');
            let exceededStr = file.name
                .substring(exceededNum + 1, file.name.length)
                .trim()
                .toLowerCase();
            if (exceededStr && this.formatArr.indexOf(exceededStr) > -1) {
                this.formItem.file = file;
                this.showSelectBucket = false;
                if (this.imageArr.includes(exceededStr)) {
                    this.showSelectBucket = true;
                    this.formItem.bucket = 'images';
                    this.formItem.type = 'images';
                } else if (this.docsArr.includes(exceededStr)) {
                    this.formItem.bucket = 'docs';
                    this.formItem.type = 'docs';
                } else if (this.othersArr.includes(exceededStr)) {
                    this.formItem.bucket = 'files';
                    this.formItem.type = 'files';
                } else if (this.videoArr.includes(exceededStr)) {
                    this.formItem.bucket = 'videos';
                    this.formItem.type = 'videos';
                } else if (this.audioArr.includes(exceededStr)) {
                    this.formItem.bucket = 'audios';
                    this.formItem.type = 'audios';
                } else if (exceededStr == 'glb') {
                    this.formItem.bucket = 'relay';
                    this.formItem.type = 'glb';
                } else {
                    this.formItem.bucket = 'files';
                    this.formItem.type = 'files';
                }
                return false;
            } else {
                this.formItem.file = null;
                this.formItem.bucket = '';
                this.formItem.type = '';
                this.$Message.error({
                    content: '不支持当前文件类型',
                    duration: 3
                });
                return false;
            }
        },
        formBtn() {
            return new Promise((resolve, reject) => {
                let _this = this;
                debugger;
                if (!this.formItem.file) {
                    _this.$Message.warning({
                        content: '请先选择文件！',
                        duration: 2
                    });
                    return;
                }
                let formData = new window.FormData();
                formData.append('file', _this.formItem.file);
                let file = {
                    name: this.onlyFileName //this.formItem.file.name
                };
                _this.loading = true;
                _this
                    .axios({
                        method: 'post',
                        url: `${_this.upLoadUrl}?visibility=person&bucket=${this.formItem.bucket}&type=${this.formItem.type}`,
                        data: formData,
                        headers: {
                            'Content-type': 'multipart/form-data'
                        },
                        onUploadProgress: (progressEvent) => {
                            //解决导入过程中关闭了modal,再选择文件，会显示上次导入的进度级速度问题
                            if (
                                file.name &&
                                _this.onlyFileName &&
                                file.name != _this.onlyFileName
                            ) {
                                return;
                            }
                            var complete = Math.floor(
                                (progressEvent.loaded / progressEvent.total) * 100
                            );
                            _this.progress = complete;
                            function getspeed() {
                                var aaspeed = Number(progressEvent.loaded - _this.loaded);
                                _this.loaded = progressEvent.loaded;
                                if (aaspeed > 1024 * 1024) {
                                    _this.speed =
                                        (
                                            Math.round((aaspeed * 100) / (1024 * 1024)) / 100
                                        ).toString() + 'MB/s';
                                } else {
                                    _this.speed =
                                        (Math.round((aaspeed * 100) / 1024) / 100).toString() +
                                        'KB/s';
                                }
                            }
                            setInterval(getspeed(), 1000);
                        }
                    })
                    .then((res) => {
                        if (res.data.code == 1) {
                            _this.formItem.file = null;
                            if (_this.progress === 100) {
                                // _this.$Message.success({
                                //     content: '创建成功！',
                                //     duration: 2
                                // });
                            }
                            setTimeout(() => {
                                _this.loading = false;
                                this.isUpdataing = false;
                                this.uploadShow = false;
                            }, 2000);
                            resolve({
                                path: res.data.data,
                                fileName: res.data.info.originalName,
                                fileId: res.data.info.id
                            });
                        } else {
                            _this.loading = false;
                            this.formItem.file = null;
                            this.speed = 0;
                            this.loaded = 0;
                            this.fileSize = 0;
                            this.progress = 0;
                            this.isUpdataing = false;
                            this.uploadShow = false;
                            _this.$Message.error({
                                content: res.data.message,
                                duration: 3
                            });
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                        _this.$Message.error('服务器连接失败！');
                        _this.loading = false;
                    });
            });
        }
    }
};
</script>
<style scoped></style>
